#include "button_handler.h"

#include "application.h"
#include "board.h"
#include "esp_log.h"

#define TAG "ButtonHandler"

ButtonHandler::ButtonHandler() {}

ButtonHandler::~ButtonHandler() {}

void ButtonHandler::Init() {
    bool res = Board::GetInstance().GetButtonInfo(button_count_, buttons_);

    if (button_count_ == 0 || res == false) {
        ESP_LOGW(TAG, "Not button found");
        return;
    }

    for (int i = 0; i < button_count_; ++i) {
        RegisterCallbacks(static_cast<ButtonRole>(i), buttons_[i]);
    }

    ESP_LOGI(TAG, "ButtonHandler initialized with %d buttons", button_count_);
}

void ButtonHandler::Deinit() {
    // 如果需要解绑或释放资源可以加逻辑
}

void ButtonHandler::RegisterCallbacks(ButtonRole role, Button* button) {
    if (!button) return;

    switch (role) {
        case ButtonRole::Boot:
            button->OnClick([] {
                ESP_LOGI(TAG, "[BOOT] Short press");
                auto& app = Application::GetInstance();
                auto& board = Board::GetInstance();
                if (app.GetDeviceState() == kDeviceStateStarting && !board.NetIsConnected()) {
                    board.ResetNetConfiguration();
                }
                app.ToggleChatState();
            });
            button->OnLongPress([] { ESP_LOGI(TAG, "[BOOT] Long press - reset WiFi"); });
            break;

        case ButtonRole::VolumeUp:
            button->OnClick([] {
                ESP_LOGI(TAG, "[VOL+] Short press - volume up");
                auto codec = Board::GetInstance().GetAudioCodec();
                int volume = codec->output_volume();
                volume = std::min(volume + 10, 100);  // 限制最大音量为100
                codec->SetOutputVolume(volume);
            });
            button->OnLongPress([] { ESP_LOGI(TAG, "[VOL+] Long press - max volume"); });
            break;

        case ButtonRole::VolumeDown:
            button->OnClick([] {
                ESP_LOGI(TAG, "[VOL-] Short press - volume down");
                auto codec = Board::GetInstance().GetAudioCodec();
                int volume = codec->output_volume();
                volume = std::max(volume - 10, 0);  // 限制最小音量为0
                codec->SetOutputVolume(volume);
            });
            button->OnLongPress([] { ESP_LOGI(TAG, "[VOL-] Long press - mute"); });
            break;

        default:
            ESP_LOGW(TAG, "Unhandled button role");
            break;
    }
}
